﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using System.Xml;
using BLL;
using Model;
using System.Web.Security;
using System.Data;
using System.Net;
using Newtonsoft.Json;

public partial class _Default : WeiPage
{
    WeiXinRequestBO wbo = new WeiXinRequestBO();
    logBO lbo = new logBO();
    qaBO qbo = new qaBO();
    GroupBuyingBO gbo = new GroupBuyingBO();
    informationBO ibo = new informationBO();
    PersonInfoBO pbo = new PersonInfoBO();
    QMPersonBO qmbo = new QMPersonBO();
    CUST_FANSBO fanbo = new CUST_FANSBO();
    const string Token = "niting";		//与微信平台那边填写的token一致
    protected void Page_Load(object sender, EventArgs e)
    {
        
        string postStr = "";
        if (Request.HttpMethod.ToLower() == "post")
        {
            Stream s = System.Web.HttpContext.Current.Request.InputStream;
            byte[] b = new byte[s.Length];
            s.Read(b, 0, (int)s.Length);
            postStr = Encoding.UTF8.GetString(b);

            if (!string.IsNullOrEmpty(postStr))
            {
                //封装请求类
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(postStr);
                XmlElement rootElement = doc.DocumentElement;

                XmlNode MsgType = rootElement.SelectSingleNode("MsgType");

                WeiXinRequest requestXML = new WeiXinRequest();
                requestXML.ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText;
                requestXML.FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText;
                requestXML.CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText;
                requestXML.Content = "";
                requestXML.EventKey = "";
                requestXML.Label = "";
                requestXML.Location_X = "";
                requestXML.Location_Y = "";
                requestXML.MsgId = "";
                requestXML.PicUrl = "";
                requestXML.resxml = "";
                requestXML.Scale = "";
                requestXML.Wxevent = "";

                requestXML.MsgType = MsgType.InnerText;

                if (requestXML.MsgType == "text")
                {
                    requestXML.Content = rootElement.SelectSingleNode("Content").InnerText;
                    requestXML.MsgId = rootElement.SelectSingleNode("MsgId").InnerText;
                }
                else if (requestXML.MsgType == "location")
                {
                    requestXML.Location_X = rootElement.SelectSingleNode("Location_X").InnerText;
                    requestXML.Location_Y = rootElement.SelectSingleNode("Location_Y").InnerText;
                    requestXML.Scale = rootElement.SelectSingleNode("Scale").InnerText;
                    requestXML.Label = rootElement.SelectSingleNode("Label").InnerText;
                }
                else if (requestXML.MsgType == "image")
                {
                    requestXML.PicUrl = rootElement.SelectSingleNode("PicUrl").InnerText;
                }
                else if (requestXML.MsgType == "event")
                {
                    requestXML.Wxevent = rootElement.SelectSingleNode("Event").InnerText;

                    if (requestXML.Wxevent.ToLower() == "location")  //高级接口获取到的地理位置
                    {
                        requestXML.Location_X = rootElement.SelectSingleNode("Latitude").InnerText;  //纬度
                        requestXML.Location_Y = rootElement.SelectSingleNode("Longitude").InnerText;  //经度
                        requestXML.Scale = rootElement.SelectSingleNode("Precision").InnerText;  //精度
                    }
                    else
                    {
                        requestXML.EventKey = rootElement.SelectSingleNode("EventKey").InnerText;
                    }
                }
                WriteTxt("----------粉丝发送过来的消息，消息类型：" + requestXML.MsgType + "----------：" + postStr);
                //回复消息
                ResponseMsg(requestXML);
            }
        }
        else
        {
            // WriteTxt("异常：");
            Valid();
        }
    }

    /// <summary>
    /// 验证微信签名
    /// </summary>
    /// * 将token、timestamp、nonce三个参数进行字典序排序
    /// * 将三个参数字符串拼接成一个字符串进行sha1加密
    /// * 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信。
    /// <returns></returns>
    private bool CheckSignature()
    {
        string signature = Request.QueryString["signature"];
        string timestamp = Request.QueryString["timestamp"];
        string nonce = Request.QueryString["nonce"];
        string[] ArrTmp = { Token, timestamp, nonce };
        Array.Sort(ArrTmp);     //字典排序
        string tmpStr = string.Join("", ArrTmp);
        tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
        tmpStr = tmpStr.ToLower();
        if (tmpStr == signature)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private void Valid()
    {
        string echoStr = Request.QueryString["echoStr"];
        if (CheckSignature())
        {
            if (!string.IsNullOrEmpty(echoStr))
            {
                Response.Write(echoStr);
                Response.End();
            }
        }
    }

    /// <summary>
    /// 回复消息(微信信息返回)
    /// </summary>
    /// <param name="weixinXML"></param>
    private void ResponseMsg(WeiXinRequest requestXML)
    {
        string sql = "";
        string resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime>";
        try
        {
            Session["FromUserName"] = requestXML.FromUserName;  //保存微信号ID

            if (requestXML.MsgType == "text")
            {
                int count = 0;
            
                information i = ibo.GetModel(requestXML.Content.Trim(), 1);
                if (i != null)
                {
                    switch (i.MsgType)
                    {
                        case "text":
                            resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + i.Content + "]]></Content><FuncFlag>0</FuncFlag></xml>";
                            break;
                        case "news":
                            resxml += "<MsgType><![CDATA[news]]></MsgType><ArticleCount>1</ArticleCount><Articles>";
                            resxml += "<item><Title><![CDATA[" + i.Title + "]]></Title><Description><![CDATA[" + i.Description + "]]></Description><PicUrl><![CDATA[" + i.PicUrl + "]]></PicUrl><Url><![CDATA[" + (i.fulltextUrl.Contains("?id") ? (i.fulltextUrl + "&FromUserName=" + requestXML.FromUserName + "&ToUserName=" + requestXML.ToUserName + "") : (i.fulltextUrl + "?FromUserName=" + requestXML.FromUserName + "&ToUserName=" + requestXML.ToUserName + "")) + "]]></Url></item>";//URL是点击之后跳转去那里，这里跳转到百度
                            resxml += "</Articles><FuncFlag>0</FuncFlag></xml>";
                            break;
                        case "music":
                            resxml += string.Format(@"<MsgType><![CDATA[music]]></MsgType>
                                 <Music>
                                 <Title><![CDATA[{0}]]></Title>
                                 <Description><![CDATA[{1}]]></Description>
                                 <MusicUrl><![CDATA[{2}]]></MusicUrl>
                                 <HQMusicUrl><![CDATA[{2}]]></HQMusicUrl>
                                 </Music>
                                 <FuncFlag>0</FuncFlag>
                                 </xml>", i.Title, i.Description, i.PicUrl);
                            break;
                        default:
                            //resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[感谢您的支持]]></Content><FuncFlag>0</FuncFlag></xml>";
                            break;
                    }
                }
                else
                {
                    information n = ibo.GetModel("", 3); //自动回复
                    if (n != null)
                    {
                        switch (n.MsgType)
                        {
                            case "text":
                                resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + n.Content + "]]></Content><FuncFlag>0</FuncFlag></xml>";
                                break;
                            case "news":
                                resxml += "<MsgType><![CDATA[news]]></MsgType><ArticleCount>1</ArticleCount><Articles>";
                                resxml += "<item><Title><![CDATA[" + n.Title + "]]></Title><Description><![CDATA[" + n.Description + "]]></Description><PicUrl><![CDATA[" + n.PicUrl + "]]></PicUrl><Url><![CDATA[" + (i.fulltextUrl.Contains("?id") ? (i.fulltextUrl + "&FromUserName=" + requestXML.FromUserName + "&ToUserName=" + requestXML.ToUserName + "") : (i.fulltextUrl + "?FromUserName=" + requestXML.FromUserName + "&ToUserName=" + requestXML.ToUserName + "")) + "]]></Url></item>";//URL是点击之后跳转去那里，这里跳转到百度
                                resxml += "</Articles><FuncFlag>0</FuncFlag></xml>";
                                break;
                            case "music":
                                resxml += string.Format(@"<MsgType><![CDATA[music]]></MsgType>
                                 <Music>
                                 <Title><![CDATA[{0}]]></Title>
                                 <Description><![CDATA[{1}]]></Description>
                                 <MusicUrl><![CDATA[{2}]]></MusicUrl>
                                 <HQMusicUrl><![CDATA[{2}]]></HQMusicUrl>
                                 </Music>
                                 <FuncFlag>0</FuncFlag>
                                 </xml>", n.Title, n.Description, n.PicUrl);
                                break;
                            default:
                                //resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[感谢您的支持]]></Content><FuncFlag>0</FuncFlag></xml>";
                                break;
                        }
                    }
                    else
                    {
                        // resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[感谢您的支持]]></Content><FuncFlag>0</FuncFlag></xml>";
                    }
                }
             
            }
      
            else if (requestXML.MsgType == "event")
            {
                CUST_FANS fans = new CUST_FANS();
                if (requestXML.Wxevent == "CLICK")
                {
                    List<information> list = ibo.GetModelList(string.Format("  keywords LIKE '%{0}%' AND replytype={1}", requestXML.EventKey, 4));
                    if (list.Count == 1 || (list.Count > 1 && list[0].MsgType != "news"))
                    {
                        information f = list[0];// ibo.GetModel(requestXML.EventKey, 4); //自定义菜单回复

                        if (f != null)
                        {
                   
                            switch (f.MsgType)
                            {
                                case "text":
                                    resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + f.Content + "]]></Content><FuncFlag>0</FuncFlag></xml>";
                                    break;
                                case "news":
                                    resxml += "<MsgType><![CDATA[news]]></MsgType><ArticleCount>1</ArticleCount><Articles>";
                                    resxml += "<item><Title><![CDATA[" + f.Title + "]]></Title><Description><![CDATA[" + f.Description + "]]></Description><PicUrl><![CDATA[" + f.PicUrl + "]]></PicUrl><Url><![CDATA[" + (f.fulltextUrl.Contains("?id") ? (f.fulltextUrl + "&FromUserName=" + requestXML.FromUserName + "&ToUserName=" + requestXML.ToUserName + "") : (f.fulltextUrl + "?FromUserName=" + requestXML.FromUserName + "&ToUserName=" + requestXML.ToUserName + "")) + "]]></Url></item>";//URL是点击之后跳转去那里，这里跳转到百度
                                    resxml += "</Articles><FuncFlag>0</FuncFlag></xml>";
                                    break;
                                case "music":
                                    resxml += string.Format(@"<MsgType><![CDATA[music]]></MsgType>
                                 <Music>
                                 <Title><![CDATA[{0}]]></Title>
                                 <Description><![CDATA[{1}]]></Description>
                                 <MusicUrl><![CDATA[{2}]]></MusicUrl>
                                 <HQMusicUrl><![CDATA[{2}]]></HQMusicUrl>
                                 </Music>
                                 <FuncFlag>0</FuncFlag>
                                 </xml>", f.Title, f.Description, f.PicUrl);
                                    break;
                                default:
                                    //resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[感谢您的支持]]></Content><FuncFlag>0</FuncFlag></xml>";
                                    break;
                            }
                          

                        }
                    }
                    else if (list.Count > 1) //多图
                    {
                        int count = list.Count;
                        resxml += "<MsgType><![CDATA[news]]></MsgType><ArticleCount>" + count + "</ArticleCount><Articles>";
                        for (int i = 0; i < count; i++)
                        {
                            resxml += "<item><Title><![CDATA[" + list[i].Title + "]]></Title><Description><![CDATA[" + list[i].Description + "]]></Description><PicUrl><![CDATA[" + list[i].PicUrl + "]]></PicUrl><Url><![CDATA[" + (list[i].fulltextUrl.Contains("?id") ? (list[i].fulltextUrl + "&FromUserName=" + requestXML.FromUserName + "&ToUserName=" + requestXML.ToUserName + "") : (list[i].fulltextUrl + "?FromUserName=" + requestXML.FromUserName + "&ToUserName=" + requestXML.ToUserName + "")) + "]]></Url></item>";//URL是点击之后跳转去那里，这里跳转到百度
                        }
                        resxml += "</Articles><FuncFlag>0</FuncFlag></xml>";
                    }
                }
                else if (requestXML.Wxevent == "unsubscribe")
                {
                    //取消关注 把粉丝表更新状态为0
                   CUST_FANS cfan = fanbo.GetModel(requestXML.FromUserName);
                   fans.NAME = cfan.NAME;
                   fans.GENDER = cfan.GENDER;
                   fans.REGION = cfan.REGION;
                   fans.FROMUSERNAME = cfan.FROMUSERNAME;
                   fans.IMAGE = cfan.IMAGE;
                   fans.STATUS = 0;
                   //fans.NOTICE_DATE = cfan.NOTICE_DATE;关注日期
                   fans.CREATE_DATE = cfan.CREATE_DATE;
                   fans.CREATE_USER =cfan.CREATE_USER;
                   fans.CANCEL_DATE =UnixTimeToTime(requestXML.CreateTime);
                   fanbo.Update(fans);

                }
                else if (requestXML.Wxevent.ToLower() == "location") //获取地理位置
                {

                }
                //关注
                else
                {
                    //获取Token字符串
                    string access_token = Token();
                    //获取用户信息列表
                    string info = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token + "&openid=" + requestXML.FromUserName + "&lang=zh_CN";
                    string infomes = PostRequestGet(info);
                    Info winfo = JsonConvert.DeserializeObject<Info>(infomes);

                    //把用户的信息存到粉丝表
                    fans.NAME = winfo.nickname;
                    fans.GENDER = winfo.sex=="1"? true:false;
                    fans.REGION = winfo.country + winfo + winfo.province + winfo.city;
                    fans.FROMUSERNAME = winfo.openid;
                    fans.IMAGE = winfo.headimgurl;
                    fans.STATUS = 1;
                    fans.NOTICE_DATE =DateTime.Parse( winfo.subscribe_time);
                    fans.CANCEL_DATE =DateTime.Parse("1900-01-01");
                    fans.CREATE_DATE = DateTime.Now;
                    fans.CREATE_USER = "system";
                    fanbo.Add(fans);
                   
                    List<information> list = ibo.GetModelList(string.Format("   replytype={0}", 2));                       
                        if (list.Count == 1 || (list.Count > 1 && list[0].MsgType != "news"))
                        {
                            information i = list[0];
                            if (i != null)
                            {
                                switch (i.MsgType)
                                {
                                    case "text":
                                        resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + i.Content + "]]></Content><FuncFlag>0</FuncFlag></xml>";
                                        break;
                                    case "news":
                                        resxml += "<MsgType><![CDATA[news]]></MsgType><ArticleCount>1</ArticleCount><Articles>";
                                        resxml += "<item><Title><![CDATA[" + i.Title + "]]></Title><Description><![CDATA[" + i.Description + "]]></Description><PicUrl><![CDATA[" + i.PicUrl + "]]></PicUrl><Url><![CDATA[" + (i.fulltextUrl.Contains("?id") ? (i.fulltextUrl + "&FromUserName=" + requestXML.FromUserName + "&ToUserName=" + requestXML.ToUserName + "") : (i.fulltextUrl + "?FromUserName=" + requestXML.FromUserName + "&ToUserName=" + requestXML.ToUserName + "")) + "]]></Url></item>";//URL是点击之后跳转去那里，这里跳转到百度
                                        resxml += "</Articles><FuncFlag>0</FuncFlag></xml>";
                                        break;
                                    case "music":
                                        resxml += string.Format(@"<MsgType><![CDATA[music]]></MsgType>
                                 <Music>
                                 <Title><![CDATA[{0}]]></Title>
                                 <Description><![CDATA[{1}]]></Description>
                                 <MusicUrl><![CDATA[{2}]]></MusicUrl>
                                 <HQMusicUrl><![CDATA[{2}]]></HQMusicUrl>
                                 </Music>
                                 <FuncFlag>0</FuncFlag>
                                 </xml>", i.Title, i.Description, i.PicUrl);
                                        break;
                                    default:
                                        //resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[感谢您的关注]]></Content><FuncFlag>0</FuncFlag></xml>";
                                        break;
                                }
                            }
                            else
                            {
                                // resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[感谢您的关注]]></Content><FuncFlag>0</FuncFlag></xml>";
                            }
                        }
                        else if (list.Count > 1) //多图
                        {
                            int count = list.Count;
                            resxml += "<MsgType><![CDATA[news]]></MsgType><ArticleCount>" + count + "</ArticleCount><Articles>";
                            for (int i = 0; i < count; i++)
                            {
                                resxml += "<item><Title><![CDATA[" + list[i].Title + "]]></Title><Description><![CDATA[" + list[i].Description + "]]></Description><PicUrl><![CDATA[" + list[i].PicUrl + "]]></PicUrl><Url><![CDATA[" + (list[i].fulltextUrl.Contains("?id") ? (list[i].fulltextUrl + "&FromUserName=" + requestXML.FromUserName + "&ToUserName=" + requestXML.ToUserName + "") : (list[i].fulltextUrl + "?FromUserName=" + requestXML.FromUserName + "&ToUserName=" + requestXML.ToUserName + "")) + "]]></Url></item>";//URL是点击之后跳转去那里，这里跳转到百度
                            }
                            resxml += "</Articles><FuncFlag>0</FuncFlag></xml>";

                        }
                }
                requestXML.resxml = resxml;
                wbo.Add(requestXML);
            }
        }
        catch (Exception ex)
        {
            //WriteTxt("异常：" + ex.Message);
            //WriteTxt(sql);
            resxml += "<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + ex.Message.ToString() + "]]></Content><FuncFlag>0</FuncFlag></xml>";
            Response.Write(resxml);
        }
        WriteTxt("返回给粉丝的消息：" + resxml);

        Response.Write(resxml);
        Response.End();
    }



    /// <summary>
    /// unix时间转换为datetime
    /// </summary>
    /// <param name="timeStamp"></param>
    /// <returns></returns>
    private DateTime UnixTimeToTime(string timeStamp) 
    {
        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        long lTime = long.Parse(timeStamp + "0000000");
        TimeSpan toNow = new TimeSpan(lTime);
        return dtStart.Add(toNow);
    }

    /// <summary>
    /// datetime转换为unixtime
    /// </summary>
    /// <param name="time"></param>
    /// <returns></returns>
    private int ConvertDateTimeInt(System.DateTime time)
    {
        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
        return (int)(time - startTime).TotalSeconds;
    }

    /// <summary>
    /// 记录bug，以便调试
    /// </summary>
    /// 
    /// <returns></returns>
    public bool WriteTxt(string str)
    {
        try
        {
            //FileStream fs = new FileStream(@"D:\WeiXin\web\buglog.txt", FileMode.Append);
            //StreamWriter sw = new StreamWriter(fs);
            ////开始写入
            //sw.WriteLine(str);
            ////清空缓冲区
            //sw.Flush();
            ////关闭流
            //sw.Close();
            //fs.Close();
            log l = new log();
            l.Con = str;
            l.Time = DateTime.Now;
            lbo.Add(l);
        }
        catch (Exception)
        {
            return false;
        }
        return true;

    }

    class Info
    {
        public int subscribe;
        public string openid;
        public string nickname;
        public string sex;
        public string language;
        public string city;
        public string province;
        public string country;
        public string headimgurl;
        public string subscribe_time;

    }


    //发送GET请求
    public string PostRequestGet(string url)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = "GET";  //定义请求对象，并设置好请求URL地址      
        //request.ProtocolVersion = HttpVersion.Version10;
        //request.ContentType = "image/jpg";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();    //定义响应对象，request在调用GetResponse方法事执行请求了，而不是在HttpWebRequest.Create的时候执行。
        //response.ContentType = "image/jpg";
        Stream stream = response.GetResponseStream(); //定义一个流对象，来获取响应流
        StreamReader sr = new StreamReader(stream, Encoding.UTF8);  //定义一个流读取对象，读取响应流
        string responseHTML = sr.ReadToEnd();
        return responseHTML;
    }
   

    
}